Préparation de l’environnement de travail

library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.2     ✔ readr     2.1.4
## ✔ forcats   1.0.0     ✔ stringr   1.5.0
## ✔ ggplot2   3.4.2     ✔ tibble    3.2.1
## ✔ lubridate 1.9.2     ✔ tidyr     1.3.0
## ✔ purrr     1.0.1     
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors

Chargement d’un shapefile

Un shapefile est un fichier contenant toute l’information liée à la géométrie des objets qu’il contient. Le format de fichier associé (.shp) est devenu un standard parmi tous les outils de SIG (Systèmes d’Informations Géographiques) et est notamment exploitable sous R. Attention, le fichier .shp est accompagné d’une série d’autres fichiers portant le même nom (.dbf, .xml, .shx, …) qui doivent être conservés au même endroit que le shapefile.

Le logiciel libre QGIS permet de créer/manipuler/éditer des shapefiles rapidement pour ensuite les exporter vers l’environnement R et générer des cartes. Si le logiciel est installé sur votre machine, ouvrez data/Loire_GIS.qgz.

Une fois le shapefile généré, il est nécessaire de le charger dans l’environnement R. Le package permettant la manipulation de ces fichiers est sf1.

Loire_coast <- sf::st_read('data/Loire_shapefile/coastline.shp', crs = 4326)
## Reading layer `coastline' from data source 
##   `C:\Users\rlecuyer\Desktop\Carto\data\Loire_shapefile\coastline.shp' 
##   using driver `ESRI Shapefile'
## Simple feature collection with 1 feature and 1 field
## Geometry type: POLYGON
## Dimension:     XY
## Bounding box:  xmin: -2.503909 ymin: 47.10874 xmax: -1.754918 ymax: 47.31379
## Geodetic CRS:  WGS 84

Les fonctionnalités de R base permettent de visualiser rapidement ce à quoi ressemblent les objets contenus dans ce shapefile.

plot(Loire_coast$geometry)

Le b.a.-ba de la cartographie avec R base

À partir de ces connaissances, il est possible de générer une représentation cartographique simple.

Loire_tidal_level <- sf::st_read('data/Loire_shapefile/tidal_level.shp', crs = 4326)
## Reading layer `tidal_level' from data source 
##   `C:\Users\rlecuyer\Desktop\Carto\data\Loire_shapefile\tidal_level.shp' 
##   using driver `ESRI Shapefile'
## Simple feature collection with 3 features and 2 fields
## Geometry type: MULTIPOLYGON
## Dimension:     XY
## Bounding box:  xmin: -2.503909 ymin: 47.10874 xmax: -1.754918 ymax: 47.31379
## Geodetic CRS:  WGS 84
tidal_level_color <- c('#DDDDCC', '#AACCFF', '#AAFFCC')

plot(Loire_coast$geometry, lwd = 2,
     main = "Les surfaces marnantes de l'estuaire de la Loire")

plot(Loire_tidal_level['level'],
     border = NA,
     pal = tidal_level_color,
     add = TRUE)

Pour la cartographie sous R sans utilisation de packages, ça s’arrête plus ou moins là. Une représentation cartographique plus travaillée pourrait inclure différentes informations complémentaires : flèche du nord, échelle …

Amélioration graphique : utilisation de ggplot2

Prenons ce magnifique classement des 10 plus beaux coins de pêche en France2.

France_fond <- sf::read_sf('data/Peche_fond.shp')

spot_peche <- read.csv2('data/Peche_meilleurcoin.csv') %>% 
  mutate(classement = as.numeric(rownames(.)))

head(spot_peche)
##                      lieu latitude longitude classement
## 1          La Sioule (03) 46.31218  3.297298          1
## 2          La Beaume (07) 44.48011  4.253149          2
## 3 Le Lac de l Abbaye (39) 46.52948  5.910707          3
## 4          Le Cousin (89) 47.48173  3.908853          4
## 5  Le Lac du Bourget (73) 45.73091  5.860195          5
## 6           Quiberon (56) 47.47771 -3.119289          6

Comment choisir notre prochaine destination pêche ?

Il suffit de représenter la localisation de ces dix meilleurs coins de pêche sur un fond de carte de la France métropolitaine, puis de choisir le lieu de nos prochaines vacances !

map_peche <- ggplot(spot_peche, aes(x = longitude, y = latitude)) +
  geom_sf(data = France_fond, fill = '#DDDDCC', inherit.aes = FALSE) +
  geom_point(aes(fill = factor(classement)), shape = 21, size = 1.5, stroke = .2) +
  ggrepel::geom_label_repel(aes(label = lieu), size = 2.5, point.padding = 3) +
  ggspatial::annotation_north_arrow(location = 'tr',
                                    style = ggspatial::north_arrow_nautical()) +
  ggspatial::annotation_scale(location = 'bl', width_hint = .25) +
  viridis::scale_fill_viridis('Classement', discrete = TRUE) +
  labs(x = 'Longitude', y = 'Latitude',
       title = 'Meilleurs coins de pêche français : un top 10') +
  coord_sf(xlim = c(-6, 10), ylim = c(41, 51)) +
  theme_bw()

map_peche
## Scale on map varies by more than 10%, scale bar may be inaccurate

Une approche plus exploratoire : la carte dynamique avec plotly

Une carte dynamique permet un minimum d’interaction avec la carte. Nous pouvons enfin aller voir où se trouve ce super spot de pêche sur l’île de la Réunion.

map_peche <- map_peche + geom_text(aes(label = lieu), size = 2.5, nudge_y = -.3)

plotly::ggplotly(map_peche)

Pour viser toujours plus loin : leaflet et les cartes Google

mapStates = maps::map("world", fill = TRUE, plot = FALSE)

leaflet::leaflet(data = spot_peche) %>% 
  leaflet::addTiles(urlTemplate = "https://mts1.google.com/vt/lyrs=s&hl=en&src=app&x={x}&y={y}&z={z}&s=G", attribution = 'Google') %>% 
  leaflet::setView(-1,47,5) %>% 
  leaflet::addCircleMarkers(popup = ~lieu)
## Assuming "longitude" and "latitude" are longitude and latitude, respectively

Création d’outils interactifs : l’application Shiny

Exemple concret d’application

Un exemple d’application Shiny au format HTML (associé au script script/Alose_app_shiny.R) :

https://gaspardd.shinyapps.io/CMAP/


  1. Pebesma, E., 2018. Simple Features for R: Standardized Support for Spatial Vector Data. The R Journal 10 (1), 439-446, https://doi.org/10.32614/RJ-2018-009↩︎

  2. source des données : https://petitsfrenchies.com/les-10-plus-beaux-endroits-pour-pecher-en-france/↩︎